package com.ruoyi.consumer.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.consumer.domain.*;
import com.ruoyi.consumer.service.impl.CCarServiceImpl;
import com.ruoyi.consumer.service.impl.CFillingStationServiceImpl;
import com.ruoyi.consumer.service.impl.CRequirementServiceImpl;
import com.ruoyi.consumer.service.impl.CUserServiceImpl;
import com.ruoyi.consumer.utils.WebsocketObjEncoder;
import com.ruoyi.framework.websocket.WebSocketUsers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.EncodeException;
import javax.websocket.Session;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author: lizhouwei
 * @ date : 2023/10/17
 * @description:
 */
@Api(tags = "加注需求")
@RestController
@RequestMapping("/api/requirement")
public class RequirementController {

    @Autowired
    private CUserServiceImpl userService;

    @Autowired
    private CCarServiceImpl carService;

    @Autowired
    private CRequirementServiceImpl requirementService;

    @Autowired
    private CFillingStationServiceImpl stationService;

    /**
     * 发布需求
     *
     * @param consumerId
     * @param carId
     * @param cLatitude
     * @param cLongitude
     * @param cUserName
     * @param cUserPhone
     * @param carImg
     * @param carPlateNum
     * @param addressName
     * @param addressDetail
     * @return
     */
    @ApiOperation("发布需求")
    @PostMapping("/publishRequirement")
    public AjaxResult publishRequirement(@ApiParam(value = "消费者id", required = true) Integer consumerId,
                                         @ApiParam(value = "车辆id", required = true) Integer carId,
                                         @ApiParam(value = "消费者所在精度", required = true) String cLatitude,
                                         @ApiParam(value = "消费者所在纬度", required = true) String cLongitude,
                                         @ApiParam(value = "需求预定时间", required = true) String requireTime,
                                         @ApiParam(value = "消费者姓名", required = true) String cUserName,
                                         @ApiParam(value = "消费者手机号", required = true) String cUserPhone,
                                         @ApiParam(value = "车辆照片", required = true) String carImg,
                                         @ApiParam(value = "车牌号", required = true) String carPlateNum,
                                         @ApiParam(value = "地址名字", required = true) String addressName,
                                         @ApiParam(value = "地址详情", required = true) String addressDetail) {
        Assert.notNull(consumerId, "消费者id不能为空");
        Assert.notNull(carId, "车辆id不能为空");
        Assert.notNull(requireTime, "需求预定时间不能为空");
        Assert.notNull(cLatitude, "消费者所在精度不能为空");
        Assert.notNull(cLongitude, "消费者所在纬度不能为空");
        Assert.notNull(cUserName, "消费者姓名不能为空");
        Assert.notNull(cUserPhone, "消费者手机号不能为空");
        Assert.notNull(carImg, "车辆照片不能为空");
        Assert.notNull(carPlateNum, "车牌号不能为空");
        Assert.notNull(addressName, "地址名字不能为空");
        Assert.notNull(addressDetail, "地址详情不能为空");

        CRequirement requirement = new CRequirement();
        //查询用户信息
        CUser cUser = userService.selectCUserByUserId(Integer.valueOf(consumerId));
        Assert.notNull(cUser, "用户不存在");
        //查询车辆信息
        CCar cCar = carService.selectCCarByCarId(Integer.valueOf(carId));
        requirement.setCarType(cCar.getVehicleType());
        Assert.notNull(cCar, "车辆不存在");
        //发布需求
        requirement.setCarId(cCar.getCarId());
        requirement.setConsumerId(cUser.getUserId());
        requirement.setcLatitude(Double.valueOf(cLatitude));
        requirement.setcLongitude(Double.valueOf(cLongitude));
        requirement.setcUserName(cUserName);
        requirement.setcUserPhone(cUserPhone);
        requirement.setCarImg(carImg);
        String pattern = "yyyy年MM月dd日 HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            Date date = sdf.parse(requireTime);
            requirement.setRequireTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        requirement.setCarPlateNum(carPlateNum);
        requirement.setAdressName(addressName);
        requirement.setAddressDetails(addressDetail);
        requirement.setStatus(0);
        int i = requirementService.insertCRequirement(requirement);
        Assert.isTrue(i > 0, "发布失败");
        //向需求大厅发送有新需求发布
        WebSocketUsers.sendMessageToUsersByText("有新需求发布");
        return AjaxResult.success("发布成功");

    }

    //取消需求
    @ApiOperation("取消需求")
    @PostMapping("/cancelRequirement")
    public AjaxResult cancelRequirement(@ApiParam(value = "需求id", required = true) Integer requirementId) {
        Assert.notNull(requirementId, "需求id不能为空");
        CRequirement requirement = requirementService.selectCRequirementByRequireId(requirementId);
        Assert.notNull(requirement, "需求不存在");
        requirement.setStatus(3);
        if (requirement.getStatus() == 1 || requirement.getStatus() == 2) {
            Assert.isTrue(requirement.getFillerId() == null, "需求已被接单，不能取消");
        }
        int i = requirementService.updateCRequirement(requirement);
        Assert.isTrue(i > 0, "取消失败");
        //向加注员发送需求取消
        Session session = WebSocketUsers.USERS.get(requirement.getFillerId().toString());
        WebSocketUsers.sendMessageToUserByText(session, "需求已取消");
        return AjaxResult.success("取消成功");
    }

    /**
     * 接单
     *
     * @param requirementId
     * @param fillerId
     * @param fillerName
     * @param fillerPhone
     * @return
     */
    @ApiOperation("接单")
    @PostMapping("/receiveRequirement")
    public AjaxResult receiveRequirement(@ApiParam(value = "需求id", required = true) Integer requirementId,
                                         @ApiParam(value = "加注员id", required = true) Integer fillerId,
                                         @ApiParam(value = "加注员姓名", required = true) String fillerName,
                                         @ApiParam(value = "加注员手机号", required = true) String fillerPhone) {
        Assert.notNull(requirementId, "需求id不能为空");
        Assert.notNull(fillerId, "加注员id不能为空");
        Assert.notNull(fillerName, "加注员姓名不能为空");
        Assert.notNull(fillerPhone, "加注员手机号不能为空");

        //查询当前加注员是否绑定加注站
        CFillingStation cFillingStation = new CFillingStation();
        cFillingStation.setFillerId(fillerId);
        List<CFillingStation> fillingStations = stationService.selectCFillingStationList(cFillingStation);
        Assert.isTrue(fillingStations.size() > 0, "加注员未绑定加注站");

        //TODO 查看当前加注员是否已经接单

        // 查询需求记录，包括版本号
        CRequirement requirement = requirementService.selectCRequirementByRequireId(requirementId);
        Assert.notNull(requirement, "需求不存在");
        // 检查需求状态是否为0，如果不是，表示需求已被接单
        if (requirement.getStatus() != 0) {
            return AjaxResult.error("需求已被接单");
        }

        // 使用乐观锁机制更新需求状态
        requirement.setFillerId(fillerId);
        requirement.setStatus(1);

        //获取当前流动加注车坐标
        CFillingStation fillingStation = new CFillingStation();
        fillingStation.setFillerId(fillerId);
        List<CFillingStation> cFillingStations = stationService.selectCFillingStationList(fillingStation);
        Double flowLat = cFillingStations.get(0).getFlowLat();
        Double flowLon = cFillingStations.get(0).getFlowLon();

        requirement.setFlowLatitude(flowLat);
        requirement.setFlowLongitude(flowLon);

        int updatedRows = requirementService.updateCRequirement(requirement);

        if (updatedRows > 0) {
            // 更新成功，向需求发布者发送加注员信息
            WebsocketObjEncoder websocketObjEncoder = new WebsocketObjEncoder();
            WebsocketObj websocketObj = new WebsocketObj();
            websocketObj.setTitle("您的需求已被接单");
            websocketObj.setData(requirement.getConsumerId().toString());

            try {
                String encodedMessage = websocketObjEncoder.encode(websocketObj);
                WebSocketUsers.sendMessageToUsersByText(encodedMessage);
            } catch (EncodeException e) {
                // 处理 EncodeException 异常
                e.printStackTrace(); // 或者执行其他处理
            }

            return AjaxResult.success("接单成功");
        } else {
            // 更新失败，可能有其他请求已经修改了需求，返回错误信息
            return AjaxResult.error("接单失败，请重试");
        }
    }

}
